import { Injectable } from '@nestjs/common'
import IORedis from 'ioredis'

@Injectable()
export class RedisService {
  private client: IORedis

  constructor() {
    this.client = new IORedis({
      host: process.env.REDIS_HOST || 'localhost',
      port: parseInt(process.env.REDIS_PORT || '6379'),
      password: process.env.REDIS_PASSWORD,
    })

    this.client.on('error', (err) => {
      console.error('Redis error:', err)
    })

    this.client.on('connect', () => {
      console.log('Connected to Redis')
    })
  }

  async get(key: string): Promise<any> {
    const value = await this.client.get(key)
    if (!value) return null

    try {
      return JSON.parse(value)
    } catch {
      return value
    }
  }

  async del(key: string): Promise<number> {
    return this.client.del(key)
  }

  async expire(key: string, seconds: number): Promise<number> {
    return this.client.expire(key, seconds)
  }

  async ttl(key: string): Promise<number> {
    return this.client.ttl(key)
  }

  async exists(key: string): Promise<number> {
    return this.client.exists(key)
  }

  async keys(pattern: string): Promise<string[]> {
    return this.client.keys(pattern)
  }
}
